﻿/// <reference path="../ExtJS/adapter/ext/ext-base.js" />
/// <reference path="../ExtJS/ext-all.js" />
/// <reference path="../ExtJS/ExtJSextend.js" />
/// <reference path="tabCommon.js" />

var dpGrid = null;
var grid = null;
var dataForm = null;
var dataWin = null;

//部门
var dpStore = new Ext.data.JsonStore({
    id: 'dpStore',
    fields: ['ID', 'FullName', 'Caption']
});
//用户
var gridStore = new Ext.data.JsonStore({
    id: 'gridStore',
    fields: ['ID', 'UserName', 'Password', 'IsAdmin', 'DepartmentID', 'FullName', 'Email', 'Mobile', 'AuthCode', 'CreateTime', 'IsStop', 'Remark']
});

//获取部门数据
function LoaddpData()
{
    tabAjaxPost('/Ajax/DepartmentList', function (json) {
        if (json.code == 1) {
            dpStore.loadData(json.data);

            LoadData(0);
        } else {
            errorMessage(json.msg);
        }
    });
}

//获取用户部门名称
function GetdpFullName(value)
{
    for (var i = 0; i < dpStore.getCount() ; i++) {
        if (dpStore.getAt(i).json.ID.toString().toLowerCase() == value.toString().toLowerCase())
            return dpStore.getAt(i).json.FullName;
    }
}

//获取用户数据
var _gridRowIndex = null;
function LoadData(rowIndex)
{
    var row = GetSelectionRow('dpGrid', rowIndex);
    if (row) {
        _gridRowIndex = rowIndex;

        tabAjaxPostData('/Ajax/UserList', { DepartmentID: row.json.ID }, function (json) {
            if (json.code == 1) {
                gridStore.loadData(json.data);
            } else {
                errorMessage(json.msg);
            }
        });
    }
    else {
        errorMessage("请先点选一行部门数据！");
    }
}

//刷新用户数据
function ReLoadData()
{
    LoadData(_gridRowIndex);
}

Ext.onReady(function () {

    //grid 行展开显示内容
    var dpGridExpander = new Ext.ux.grid.RowExpander({
        tpl: new Ext.Template(
            '<p>' + GetRowExpanderNbsp() + '<b>名称：</b>　{FullName}</p>',
            '<p>' + GetRowExpanderNbsp() + '<b>介绍：</b>　{Caption}</p>'
            )
    });

    //显示部门数据表格
    var dpGrid = new Ext.grid.GridPanel({
        id: 'dpGrid',
        scriptRow: true,
        store: dpStore,
        viewConfig: {
            firceFit: true,
            deferEmptyText: false,
            emptyText: '暂无部门数据！',
            getRowClass: function (record, index) {
                if (!(index % 2)) {
                    return 'x-grid3-row';
                } else {
                    return 'x-grid3-row-alt';
                }
            }
        },
        columns: [
            new Ext.grid.RowNumberer(),
            dpGridExpander,
            { header: '标识', width: 260, dataIndex: 'ID', sortable: true, align: 'center', hidden: true },
            { header: '名称', width: 170, dataIndex: 'FullName', sortable: true, align: 'center' },
            { header: '介绍', width: 400, dataIndex: 'Caption', sortable: true, align: 'center', hidden: true }
        ],
        plugins: dpGridExpander,
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        listeners: {
            'cellclick': function (grid, rowIndex, columnIndex, e) {
                LoadData(rowIndex);
            },
            'rowdblclick': function (grid, rowIndex, e) {
                LoadData(rowIndex);
            },
            'rowcontextmenu': function (grid, rowIndex, e) {
                e.preventDefault();
                var dpGrid_menus = new Ext.menu.Menu({
                    shadow: 'sides',
                    items: [{
                        text: '加载所属用户',
                        iconCls: 'icons-user-group',
                        handler: function () {
                            LoadData(rowIndex);
                        }
                    }]
                });
                dpGrid_menus.showAt(e.getPoint());
            }
        }
    });

    //grid 行展开显示内容
    var gridExpander_tpl = new Ext.Template(
            '<p>' + GetRowExpanderNbsp() + '<b>部门：</b>　{DepartmentID:this.dpFormat()}　&nbsp;　<b>姓名：</b>　{FullName}　&nbsp;　<b>用户名：</b>　{UserName}</p>',
            '<p>' + GetRowExpanderNbsp() + '<b>备注：</b>　{Remark}</p>'
            );
    var gridExpander = new Ext.ux.grid.RowExpander({
        tpl: gridExpander_tpl
    });
    gridExpander_tpl.dpFormat = function (data, o) {
        return GetdpFullName(data);
    }

    //显示用户数据表格
    var grid = new Ext.grid.GridPanel({
        id: 'grid',
        scriptRow: true,
        store: gridStore,
        viewConfig: {
            firceFit: true,
            deferEmptyText: false,
            emptyText: '暂无该部门用户数据！',
            getRowClass: function (record, index) {
                if (!(index % 2)) {
                    return 'x-grid3-row';
                } else {
                    return 'x-grid3-row-alt';
                }
            }
        },
        columns: [
            new Ext.grid.RowNumberer(),
            gridExpander,
            { header: '标识', width: 260, dataIndex: 'ID', sortable: true, align: 'center', hidden: true },
            { header: '用户名', width: 100, dataIndex: 'UserName', sortable: true, align: 'center' },
            { header: '管理员', width: 60, dataIndex: 'IsAdmin', sortable: true, align: 'center', renderer: SetGridBoolValue },
            {
                header: '部门', width: 80, dataIndex: 'DepartmentID', sortable: true, align: 'center',
                renderer: function (value, metaData, record, rowIndex, colIndex, store) {
                    return GetdpFullName(value);
                }
            },
            { header: '姓名', width: 80, dataIndex: 'FullName', sortable: true, align: 'center' },
            { header: '邮箱', width: 150, dataIndex: 'Email', sortable: true, align: 'center' },
            { header: '手机', width: 100, dataIndex: 'Mobile', sortable: true, align: 'center' },
            { header: '授权码', width: 250, dataIndex: 'AuthCode', sortable: true, align: 'left', hidden: true },
            { header: '创建时间', width: 150, dataIndex: 'CreateTime', sortable: true, align: 'center' },
            { header: '已停用', width: 60, dataIndex: 'IsStop', sortable: true, align: 'center', renderer: SetGridBoolValue },
            { header: '备注', width: 400, dataIndex: 'Remark', sortable: true, align: 'center', hidden: true }
        ],
        plugins: gridExpander,
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        listeners: {
            'rowdblclick': function (grid, rowIndex, e) {
                EditData(rowIndex);
            },
            'rowcontextmenu': function (grid, rowIndex, e) {
                e.preventDefault();
                var grid_menus = new Ext.menu.Menu({
                    shadow: 'sides',
                    items: [{
                        text: '编辑',
                        iconCls: 'icons-user-edit',
                        handler: function () {
                            EditData(rowIndex);
                        }
                    }, {
                        text: '刷新授权码',
                        iconCls: 'icons-user-search',
                        handler: function () {
                            UserRefAuthCode(rowIndex);
                        }
                    }, {
                        text: '停用/恢复',
                        iconCls: 'icons-user-delete',
                        handler: function () {
                            UserStop(rowIndex);
                        }
                    }]
                });
                grid_menus.showAt(e.getPoint());
            }
        }
    });


    //视图内容与布局
    var _left = new Ext.Panel({
        region: 'west',
        id: '_left',
        title: '部门列表',
        collapseMode: 'mini',
        iconCls: 'icons-department',
        split: true,
        width: 225,
        minSize: 175,
        maxSize: 275,
        layout: 'fit',
        items: [dpGrid],
        tbar: [{
            text: '刷新',
            iconCls: 'icons-department-search',
            handler: function () {
                LoaddpData();
            }
        }]
    });
    var _center = new Ext.Panel({
        region: 'center',
        layout: 'fit',
        items: [grid],
        tbar: [{
            text: '新增',
            iconCls: 'icons-user-add',
            handler: function () {
                AddData();
            }
        }, {
            text: '编辑',
            iconCls: 'icons-user-edit',
            handler: function () {
                EditData();
            }
        }, {
            text: '停用/恢复',
            iconCls: 'icons-user-delete',
            handler: function () {
                UserStop();
            }
        }, {
            text: '刷新授权码',
            iconCls: 'icons-user-search',
            handler: function () {
                UserRefAuthCode();
            }
        }, {
            text: '刷新',
            iconCls: 'icons-user-search',
            handler: function () {
                ReLoadData();
            }
        }]
    });
    var _view = new Ext.Viewport({
        layout: 'border',
        items: [_left, _center]
    });

    //加载数据
    LoaddpData();

    //创建表单
    CreateForm();

});

//新增数据
function AddData() {
    dataForm.getForm().reset();
    dataWin.setTitle("新建用户信息");
    dataWin.show();
}

//编辑行数据
function EditData(rowIndex) {
    var row = GetSelectionRow('grid', rowIndex);
    if (row) {
        dataWin.setTitle("编辑用户信息 - " + (row.json.FullName ? row.json.FullName : row.json.UserName));
        dataWin.show();
        dataForm.getForm().loadRecord(row);
    }
    else {
        errorMessage("请先点选一行数据！");
    }
}

//停用/恢复用户帐户
function UserStop(rowIndex) {
    var row = GetSelectionRow('grid', rowIndex);
    if (row) {
        Ext.Msg.confirm('温馨提示', '您确定要停用/恢复该信息吗？', function (btn) {
            if (btn == 'yes') {
                tabAjaxPostData('/Ajax/UserStop', { ID: row.json.ID }, function (json) {
                    if (json.code == 1) {
                        ReLoadData();
                    } else {
                        errorMessage(json.msg);
                    }
                });
            }
        });
    }
    else {
        errorMessage("请先点选一行数据！");
    }
}

//刷新用户授权码
function UserRefAuthCode(rowIndex) {
    var row = GetSelectionRow('grid', rowIndex);
    if (row) {
        Ext.Msg.confirm('温馨提示', '您确定要刷新该用户授权码吗？', function (btn) {
            if (btn == 'yes') {
                tabAjaxPostData('/Ajax/UserRefAuthCode', { ID: row.json.ID }, function (json) {
                    if (json.code == 1) {
                        ReLoadData();
                    } else {
                        errorMessage(json.msg);
                    }
                });
            }
        });
    }
    else {
        errorMessage("请先点选一行数据！");
    }
}

//创建表单
function CreateForm() {
    //使用表单提示
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    dataForm = new Ext.FormPanel({
        labelWidth: 60,
        labelAlign: 'right',
        border: false,
        defaultType: 'textfield',
        buttomAlign: 'center',
        bodyStyle: 'padding: 15px',
        items: [{
            inputType: 'hidden',
            name: 'ID'
        }, {
            fieldLabel: '用户名',
            name: 'UserName',
            anchor: '90%',
            allowBlank: false,
            emptyText: '请填写用户名，可修改为未占用的用户名',
            blankText: '用户名不能为空'
        }, {
            inputType: 'password',
            fieldLabel: '密码',
            name: 'Password',
            anchor: '90%',
            emptyText: '密码留空则不修改'
        }, new Ext.form.Checkbox({
            name: 'IsAdmin',
            fieldLabel: '管理员',
            boxLabel: '除admin帐户外不可以设置管理员！'
        }), new Ext.form.ComboBox({
            fieldLabel: '部门',
            name: 'DepartmentID',
            hiddenName: 'DepartmentID',
            anchor: '90%',
            allowBlank: false,
            emptyText: '请选择部门',
            blankText: '部门不能为空',
            triggerAction: 'all', //默认仅显示符合输入的项
            store: dpStore,
            displayField: 'FullName',
            valueField: 'ID',
            mode: 'local'
        }), {
            fieldLabel: '姓名',
            name: 'FullName',
            anchor: '90%',
            emptyText: '请填写用户姓名'
        }, {
            fieldLabel: '邮箱',
            name: 'Email',
            anchor: '90%',
            emptyText: '请填写用户邮箱'
        }, {
            fieldLabel: '手机',
            name: 'Mobile',
            anchor: '90%',
            emptyText: '请填写手机号（国际支持），请仔细检查输入'
        }, {
            fieldLabel: '授权码',
            name: 'AuthCode',
            anchor: '90%',
            emptyText: '授权码无需填写，亦不能修改仅可刷新'
        }, new Ext.form.Checkbox({
            name: 'IsStop',
            fieldLabel: '停用',
            boxLabel: '勾选则用户被停用不能再登陆！'
        }), {
            xtype: 'textarea',
            fieldLabel: '备注',
            name: 'Remark',
            anchor: '90%',
            emptyText: '可选填备注内容',
            maxLength: 400
        }],
        buttons: [{
            text: '提交',
            iconCls: 'icons-base-accept',
            handler: function () {
                SaveData();
            }
        }, {
            text: '退出',
            iconCls: 'icons-base-cancel',
            handler: function () {
                dataWin.hide();
            }
        }]
    });

    //表单显示的窗体
    dataWin = new Ext.Window({
        title: '用户信息',
        layout: 'fit',
        width: 400,
        height: 410,
        closeAction: 'hide',
        iconCls: 'icons-user',
        plain: true,
        modal: true,
        maskDisabled: true,
        items: dataForm
    });

}

//提交编辑
function SaveData() {
    tabFormSubmit(dataForm, '/Ajax/UserEdit', function (json) {
        if (json.code == 1) {
            alertMessage("操作成功！");
            dataWin.hide();
            ReLoadData();
        }
        else
            errorMessage(json.msg);
    });
}
